package com.px.baolaiapi.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.px.common.api.CommonResult;
import com.px.mbg.model.DeviceType;
import com.px.baolaiapi.ExcelDto.ExcelDeviceTypeDto;
import com.px.baolaiapi.execleventlistener.DeviceTypeDataListeren;
import com.px.baolaiapi.page.DeviceTypePage;
import com.px.baolaiapi.service.IDeviceTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * <p>
 * 设备类型 前端控制器
 * </p>
 *
 * @author 品讯科技
 * @since 2021-12-20
 */
@Api(tags = "设备类型管理")
@RestController
@RequestMapping("/device-type")
public class DeviceTypeController {
    @Autowired
    private IDeviceTypeService deviceTypeService;

    @ApiOperation("添加设备分类")
    @PostMapping("/addDeviceType")
    public CommonResult addDeviceType(@RequestBody @Validated DeviceType deviceType) {
        int status = deviceTypeService.addDeviceType(deviceType);
        if (status > 0) {
            return CommonResult.success(status);
        } else if (status == -1) {
            return CommonResult.failed("编码已经被占用");
        }
        return CommonResult.failed("操作失败");
    }

    @ApiOperation("变更设备分类")
    @PostMapping("/updateDeviceType")
    public CommonResult updateDeviceType(@RequestBody @Validated DeviceType deviceType) {
        int status = deviceTypeService.updateDeviceType(deviceType);
        if (status > 0) {
            return CommonResult.success(status);
        } else if (status == -1) {
            return CommonResult.failed("编码已经被占用");
        }
        return CommonResult.failed("操作失败");
    }

    @ApiOperation("删除设备分类")
    @GetMapping("/deleteDeviceType")
    public CommonResult deleteDeviceType(long id) {
        return deviceTypeService.deleteDeviceType(id);
    }

    @ApiOperation("查询设备分类-分页")
    @PostMapping("/queryDeviceTypePage")
    public CommonResult queryDeviceTypePage(@RequestBody DeviceTypePage page) {
        return CommonResult.success(deviceTypeService.queryDeviceTypePage(page));
    }

    @ApiOperation("查询设备分类-全部")
    @GetMapping("/queryDeviceTypeAll")
    public CommonResult queryDeviceTypeAll() {
        return CommonResult.success(deviceTypeService.list());
    }


    @ApiOperation("下载设备分类模板")
    @GetMapping("downloadTemplete")
    public void downloadTemplete(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            String fname = "设备分类Excel模板";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(fname, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), ExcelDeviceTypeDto.class).sheet("分类信息").doWrite(new ArrayList());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSONObject.parseObject(CommonResult.failed("下载文件失败" + e.getMessage()).toString()));
        }
    }


    @ApiOperation("下载设备分类信息")
    @GetMapping("downloadDeviceType")
    public void downloadDeviceType(@RequestParam("code") String code, @RequestParam("name") String name, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            String fname = "设备分类数据";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(fname, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            DeviceTypePage deviceTypePage = new DeviceTypePage();
            deviceTypePage.setCode(code);
            deviceTypePage.setName(name);

            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), ExcelDeviceTypeDto.class).sheet("分类信息").doWrite(deviceTypeService.queryDeviceTypeList(deviceTypePage));
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSONObject.parseObject(CommonResult.failed("下载文件失败" + e.getMessage()).toString()));
        }
    }

    @ApiOperation("上传excel文件并储存数据")
    @PostMapping("/upload")
    public CommonResult upload(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), ExcelDeviceTypeDto.class, new DeviceTypeDataListeren(deviceTypeService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("上传失败");
        }
        return CommonResult.success("上传成功");
    }

}
